package com.yu.Demo02;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {

    public static void main(String[] args) {
        Resource resource = new Resource();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                resource.incr();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                resource.decr();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                resource.incr();
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                resource.decr();
            }
        },"D").start();
    }

}

class Resource{
    private int number = 0;
    Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void incr(){
        try {
            lock.lock();
            while (number!=0){
                condition.await();
            }
            number++;
            System.out.println("--------" + Thread.currentThread().getName() + "加一成功----------,值为:" + number);
            condition.signalAll();
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }

    public void decr(){
        try {
            lock.lock();
            while (number==0){
                condition.await();
            }
            number--;
            System.out.println("--------" + Thread.currentThread().getName() + "减一成功----------,值为:" + number);
            condition.signalAll();
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }
}